export default {
  install (Vue, options) {
    /**
     * 货币过滤器
     * value  金额
     * currency 货币符号  default:'$'
     * decimals 保留位数  default: 2
     * thousand 是否已千作为单位 default: false
     */
    const digitsRE = /(\d{3})(?=\d)/g;
    Vue.filter('currency', function (value, currency, decimals, thousand) {
      value = parseFloat(value);
      // 判断value 是否为空，是否是无限数
      if (!isFinite(value) || (!value && value !== 0)) return '';
      currency = currency != null ? currency : '$';
      decimals = decimals != null ? decimals : 2;
      thousand = thousand != null ? thousand : false;
      if (thousand) {
        value = value / 1000;
      }
      let stringifier = Math.abs(value).toFixed(decimals);
      let _int = decimals
        ? stringifier.slice(0, -1 - decimals)
        : stringifier;
      let i = _int.length % 3;
      let head = i > 0
        ? (_int.slice(0, i) + (_int.length > 3 ? ',' : ''))
        : '';
      let _float = decimals
        ? stringifier.slice(-1 - decimals)
        : '';
      let sign = value < 0 ? '-' : '';
      let unit = thousand ? 'k' : '';
      return sign + currency + head +
        _int.slice(i).replace(digitsRE, '$1,') +
        _float + unit
    })
  }
}
